package com.car.loan.project.xr.controller.report;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.car.loan.common.file.ExcelExportUtil;
import com.car.loan.common.utils.BeanUtils;
import com.car.loan.framework.web.domain.AjaxResult;
import com.car.loan.project.system.domain.SysUser;
import com.car.loan.project.xr.controller.ExcelFileUtil;
import com.car.loan.project.xr.service.ReportService;
import com.car.loan.project.xr.util.RedisDataUtil;
import com.car.loan.project.xr.util.bo.business.report.AuditInfoBo;
import com.car.loan.project.xr.util.bo.business.report.BusinessStatisticsBo;
import com.car.loan.project.xr.util.bo.business.report.ContractAgingBo;
import com.car.loan.project.xr.util.bo.business.report.ContractInfoBo;
import com.car.loan.project.xr.util.bo.business.report.LicenseAgingBo;
import com.car.loan.project.xr.util.bo.business.report.PaymentInfoBo;
import com.car.loan.project.xr.util.bo.business.report.RepaymentInfoBo;
import com.car.loan.project.xr.util.bo.business.report.SettleInfoBo;
import com.car.loan.project.xr.util.repayment.RepaymentPlan;
import com.car.loan.project.xr.util.repayment.RepaymentPlanParam;
import com.car.loan.project.xr.util.repayment.RepaymentPlanUtil;
import com.car.loan.project.xr.util.vo.report.AuditInfoVo;
import com.car.loan.project.xr.util.vo.report.BusinessStatisticsAmountVo;
import com.car.loan.project.xr.util.vo.report.BusinessStatisticsVo;
import com.car.loan.project.xr.util.vo.report.ContractAgingVo;
import com.car.loan.project.xr.util.vo.report.ContractInfoVo;
import com.car.loan.project.xr.util.vo.report.LicenseAgingVo;
import com.car.loan.project.xr.util.vo.report.PaymentInfoVo;
import com.car.loan.project.xr.util.vo.report.RepaymentInfoVo;
import com.car.loan.project.xr.util.vo.report.SettleInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 请看小郭同学的头
 * @author huangding
 * @date 2020/2/18 21:48
 */
@RestController
@RequestMapping("xr/report")
@Api(value = "报表管理", tags = "报表管理")
@Slf4j
public class ReportController {

    @Autowired
    private ReportService reportService;

    @Autowired
    protected HttpServletRequest request;

    @Resource
    private ExcelFileUtil excelFileUtil;


    @Autowired
    private RedisDataUtil redisDataUtil;


    @PreAuthorize("@ss.hasPermi('report:businessStatistics:list')")
    @GetMapping("businessStatistics/list")
    @ApiOperation(value = "业务统计表", response = BusinessStatisticsVo.class, responseContainer = "list")
    public AjaxResult businessStatistics(@Valid BusinessStatisticsBo businessStatisticsBo) {
        Page<BusinessStatisticsVo> businessStatisticsVoPage = reportService
            .businessStatisticsPage(businessStatisticsBo);
        Map<String, Object> result = new HashMap<>(2);
        result.put("page", businessStatisticsVoPage);
        BusinessStatisticsAmountVo businessStatisticsAmountVo = new BusinessStatisticsAmountVo();
        if (businessStatisticsVoPage.getTotal() > 0) {
            businessStatisticsAmountVo = reportService
                .businessStatisticsAmount(businessStatisticsBo);
        }
        result.put("businessStatisticsAmount", businessStatisticsAmountVo);
        return AjaxResult.success(result);
    }

    @PreAuthorize("@ss.hasPermi('report:businessStatistics:list')")
    @GetMapping("businessStatistics/excel")
    @ApiOperation(value = "业务统计表-excel")
    public void businessStatisticsExcel(@Valid BusinessStatisticsBo businessStatisticsBo,
        HttpServletResponse response) {
        businessStatisticsBo.setPageNum(1);
        businessStatisticsBo.setPageSize(999999);
        Page<BusinessStatisticsVo> businessStatisticsVoPage = reportService
            .businessStatisticsPage(businessStatisticsBo);
        InputStream templateExcelFile = excelFileUtil
            .getTemplateInputStream("business_statistics.xlsx");
        String exportFileName = "业务统计表" + LocalDate.now() + ".xlsx";
        ExcelExportUtil
            .exportByBeans(2, templateExcelFile, exportFileName, false, null,
                businessStatisticsVoPage.getRecords(),
                request, response);
    }


    @PreAuthorize("@ss.hasPermi('report:auditInfo:list')")
    @GetMapping("auditInfo/list")
    @ApiOperation(value = "审批信息表", response = AuditInfoVo.class, responseContainer = "list")
    public AjaxResult auditInfo(@Valid AuditInfoBo auditInfoBo) {
        Page<AuditInfoVo> auditInfoVoPage = reportService
            .getAuditInfoVoPage(auditInfoBo);
        //处理名称
        if (auditInfoVoPage.getTotal() > 0) {
            Map<String, SysUser> redisUserMap = redisDataUtil.getRedisUserMap();
            List<AuditInfoVo> records = auditInfoVoPage.getRecords();
            records.forEach(record -> {
                record.setBusinessApostilleName(
                    getAdminName(redisUserMap, record.getBusinessApostilleId()));
                record.setBusinessName(getAdminName(redisUserMap, record.getBusinessId()));
                record
                    .setBusinessAuditName(getAdminName(redisUserMap, record.getBusinessAuditId()));
            });
        }
        return AjaxResult.success(auditInfoVoPage);
    }

    @PreAuthorize("@ss.hasPermi('report:auditInfo:list')")
    @GetMapping("auditInfo/excel")
    @ApiOperation(value = "审批信息表-excel")
    public void auditInfoExcel(@Valid AuditInfoBo auditInfoBo,
        HttpServletResponse response) {
        auditInfoBo.setPageNum(1);
        auditInfoBo.setPageSize(999999);
        Page<AuditInfoVo> auditInfoVoPage = reportService
            .getAuditInfoVoPage(auditInfoBo);
        //处理名称
        if (auditInfoVoPage.getTotal() > 0) {
            Map<String, SysUser> redisUserMap = redisDataUtil.getRedisUserMap();
            List<AuditInfoVo> records = auditInfoVoPage.getRecords();
            records.forEach(record -> {
                record.setBusinessApostilleName(
                    getAdminName(redisUserMap, record.getBusinessApostilleId()));
                record.setBusinessName(getAdminName(redisUserMap, record.getBusinessId()));
                record
                    .setBusinessAuditName(getAdminName(redisUserMap, record.getBusinessAuditId()));
            });
        }
        InputStream templateExcelFile = excelFileUtil
            .getTemplateInputStream("audit_info.xlsx");
        String exportFileName = "审批信息表" + LocalDate.now() + ".xlsx";
        ExcelExportUtil
            .exportByBeans(2, templateExcelFile, exportFileName, false, null,
                auditInfoVoPage.getRecords(),
                request, response);
    }


    @PreAuthorize("@ss.hasPermi('report:contractAging:list')")
    @GetMapping("contractAging/list")
    @ApiOperation(value = "合同时效表", responseContainer = "list", response = ContractInfoVo.class)
    public AjaxResult contractAging(@Valid ContractAgingBo contractAgingBo) {
        Page<ContractAgingVo> contractAgingVoPage = reportService
            .getContractAgingVoPage(contractAgingBo);
        return AjaxResult.success(contractAgingVoPage);
    }

    @PreAuthorize("@ss.hasPermi('report:contractAging:list')")
    @GetMapping("contractAging/excel")
    @ApiOperation(value = "合同时效表-excel")
    public void contractAgingExcel(@Valid ContractAgingBo contractAgingBo,
        HttpServletResponse response) {
        contractAgingBo.setPageNum(1);
        contractAgingBo.setPageSize(999999);
        Page<ContractAgingVo> contractAgingVoPage = reportService
            .getContractAgingVoPage(contractAgingBo);
        InputStream templateExcelFile = excelFileUtil
            .getTemplateInputStream("contract_aging.xlsx");
        String exportFileName = "合同时效表" + LocalDate.now() + ".xlsx";
        ExcelExportUtil
            .exportByBeans(2, templateExcelFile, exportFileName, false, null,
                contractAgingVoPage.getRecords(),
                request, response);
    }

    @PreAuthorize("@ss.hasPermi('report:contractInfo:list')")
    @GetMapping("contractInfo/list")
    @ApiOperation(value = "合同信息表", response = ContractInfoVo.class, responseContainer = "list")
    public AjaxResult contractInfo(@Valid ContractInfoBo contractInfoBo) {
        Page<ContractInfoVo> contractInfoVoPage = reportService
            .getContractInfoVoPage(contractInfoBo);
        //处理名称
        if (contractInfoVoPage.getTotal() > 0) {
            Map<String, SysUser> redisUserMap = redisDataUtil.getRedisUserMap();
            List<ContractInfoVo> records = contractInfoVoPage.getRecords();
            records.forEach(record -> {
                record.setPaymentInfoName(getAdminName(redisUserMap, record.getPaymentInfoId()));
                record
                    .setContractAuditName(getAdminName(redisUserMap, record.getContractAuditId()));
                record.setDataAuditName(getAdminName(redisUserMap, record.getDataAuditId()));
                record.setContractInfoName(getAdminName(redisUserMap, record.getContractInfoId()));
            });
        }

        return AjaxResult.success(contractInfoVoPage);
    }


    @PreAuthorize("@ss.hasPermi('report:contractInfo:list')")
    @GetMapping("contractInfo/excel")
    @ApiOperation(value = "合同信息表-excel")
    public void contractInfoExcel(@Valid ContractInfoBo contractInfoBo,
        HttpServletResponse response) {
        contractInfoBo.setPageNum(1);
        contractInfoBo.setPageSize(999999);
        Page<ContractInfoVo> contractInfoVoPage = reportService
            .getContractInfoVoPage(contractInfoBo);
        //处理名称
        if (contractInfoVoPage.getTotal() > 0) {
            Map<String, SysUser> redisUserMap = redisDataUtil.getRedisUserMap();
            List<ContractInfoVo> records = contractInfoVoPage.getRecords();
            records.forEach(record -> {
                record.setPaymentInfoName(getAdminName(redisUserMap, record.getPaymentInfoId()));
                record
                    .setContractAuditName(getAdminName(redisUserMap, record.getContractAuditId()));
                record.setDataAuditName(getAdminName(redisUserMap, record.getDataAuditId()));
                record.setContractInfoName(getAdminName(redisUserMap, record.getContractInfoId()));
            });
        }
        InputStream templateExcelFile = excelFileUtil
            .getTemplateInputStream("contract_info.xlsx");
        String exportFileName = "合同信息表" + LocalDate.now() + ".xlsx";
        ExcelExportUtil
            .exportByBeans(2, templateExcelFile, exportFileName, false, null,
                contractInfoVoPage.getRecords(),
                request, response);
    }


    @PreAuthorize("@ss.hasPermi('report:licenseAging:list')")
    @GetMapping("licenseAging/list")
    @ApiOperation(value = "牌证时效表", response = LicenseAgingVo.class, responseContainer = "list")
    public AjaxResult licenseAging(@Valid LicenseAgingBo licenseAgingBo) {
        Page<LicenseAgingVo> licenseAgingVoPage = reportService
            .getLicenseAgingVoPage(licenseAgingBo);
        return AjaxResult.success(licenseAgingVoPage);
    }

    @PreAuthorize("@ss.hasPermi('report:licenseAging:list')")
    @GetMapping("licenseAging/excel")
    @ApiOperation(value = "牌证时效表-excel", response = LicenseAgingVo.class, responseContainer = "list")
    public void licenseAgingExcel(@Valid LicenseAgingBo licenseAgingBo,
        HttpServletResponse response) {
        licenseAgingBo.setPageNum(1);
        licenseAgingBo.setPageSize(999999);
        Page<LicenseAgingVo> licenseAgingVoPage = reportService
            .getLicenseAgingVoPage(licenseAgingBo);
        InputStream templateExcelFile = excelFileUtil
            .getTemplateInputStream("license_aging.xlsx");
        String exportFileName = "牌证时效表" + LocalDate.now() + ".xlsx";
        ExcelExportUtil
            .exportByBeans(2, templateExcelFile, exportFileName, false, null,
                licenseAgingVoPage.getRecords(),
                request, response);
    }


    @PreAuthorize("@ss.hasPermi('report:paymentInfo:list')")
    @GetMapping("paymentInfo/list")
    @ApiOperation(value = "付款信息表", responseContainer = "list", response = PaymentInfoVo.class)
    public AjaxResult paymentInfo(@Valid PaymentInfoBo paymentInfoBo) {
        Page<PaymentInfoVo> paymentInfoVoPage = reportService
            .getPaymentInfoVoPage(paymentInfoBo);
        return AjaxResult.success(paymentInfoVoPage);
    }

    @PreAuthorize("@ss.hasPermi('report:paymentInfo:list')")
    @GetMapping("paymentInfo/excel")
    @ApiOperation(value = "付款信息表-excel", responseContainer = "list", response = PaymentInfoVo.class)
    public void paymentInfoExcel(@Valid PaymentInfoBo paymentInfoBo,
        HttpServletResponse response) {
        paymentInfoBo.setPageNum(1);
        paymentInfoBo.setPageSize(999999);
        Page<PaymentInfoVo> paymentInfoVoPage = reportService
            .getPaymentInfoVoPage(paymentInfoBo);
        InputStream templateExcelFile = excelFileUtil
            .getTemplateInputStream("payment_info.xlsx");
        String exportFileName = "付款信息表" + LocalDate.now() + ".xlsx";
        ExcelExportUtil
            .exportByBeans(2, templateExcelFile, exportFileName, false, null,
                paymentInfoVoPage.getRecords(),
                request, response);
    }

    @PreAuthorize("@ss.hasPermi('report:settleInfo:list')")
    @GetMapping("settleInfo/list")
    @ApiOperation(value = "结算信息表", response = SettleInfoVo.class, responseContainer = "list")
    public AjaxResult settleInfo(@Valid SettleInfoBo settleInfoBo) {
        Page<SettleInfoVo> settleInfoVoPage = reportService
            .getSettleInfoVoPage(settleInfoBo);
        return AjaxResult.success(settleInfoVoPage);
    }

    @PreAuthorize("@ss.hasPermi('report:settleInfo:list')")
    @GetMapping("settleInfo/excel")
    @ApiOperation(value = "结算信息表-excel", response = SettleInfoVo.class, responseContainer = "list")
    public void settleInfoExcel(@Valid SettleInfoBo settleInfoBo,
        HttpServletResponse response) {
        settleInfoBo.setPageNum(1);
        settleInfoBo.setPageSize(999999);
        Page<SettleInfoVo> settleInfoVoPage = reportService
            .getSettleInfoVoPage(settleInfoBo);
        InputStream templateExcelFile = excelFileUtil
            .getTemplateInputStream("settle_info.xlsx");
        String exportFileName = "结算信息表" + LocalDate.now() + ".xlsx";
        ExcelExportUtil
            .exportByBeans(2, templateExcelFile, exportFileName, false, null,
                settleInfoVoPage.getRecords(),
                request, response);
    }

    @PreAuthorize("@ss.hasPermi('report:repaymentInfo:list')")
    @GetMapping("repaymentInfo/list")
    @ApiOperation("还款信息表")
    public AjaxResult repaymentInfo(@Valid RepaymentInfoBo repaymentInfoBo,
        HttpServletResponse response) {
        if (repaymentInfoBo.isExport()) {
            repaymentInfoBo.setPageNum(1);
            repaymentInfoBo.setPageSize(999999);
        }
        Page<RepaymentInfoVo> repaymentInfoVoPage = reportService
            .getRepaymentInfoVoPage(repaymentInfoBo);
        if (repaymentInfoVoPage.getTotal() > 0) {
            List<RepaymentInfoVo> records = repaymentInfoVoPage.getRecords();
            records.forEach(record -> {
                RepaymentPlanParam repaymentPlanParam = new RepaymentPlanParam();
                BeanUtils.copyBeanProp(repaymentPlanParam, record);
                repaymentPlanParam.setFirstStatementDate(record.getFirstRepayDate());

                String lastRepaymentDate = record.getLastRepaymentDate();
                if (StringUtils.isBlank(lastRepaymentDate)) {
                    lastRepaymentDate = RepaymentPlanUtil
                        .getLastRepaymentDate(record.getGracePeriod(), record.getTerm(),
                            record.getFirstRepayDate());
                }

                record.setLastRepaymentDate(lastRepaymentDate);
                RepaymentPlan currentRepaymentPlan = RepaymentPlanUtil
                    .getCurrentRepaymentPlan(repaymentPlanParam,
                        LocalDate.parse(lastRepaymentDate));

                if (!currentRepaymentPlan.getTerm().equals(repaymentPlanParam.getTerm())) {
                    record.setCurrentTerm(currentRepaymentPlan.getTerm());
                    record.setRepayAmount(currentRepaymentPlan.getMonthRepayAmount());
                }
            });
        }
        if (repaymentInfoBo.isExport()) {
            InputStream templateExcelFile = excelFileUtil
                .getTemplateInputStream("repayment_info.xlsx");
            String exportFileName = "还款信息表" + LocalDate.now() + ".xlsx";
            ExcelExportUtil
                .exportByBeans(2, templateExcelFile, exportFileName, false, null,
                    repaymentInfoVoPage.getRecords(),
                    request, response);
            return null;
        }
        return AjaxResult.success(repaymentInfoVoPage);
    }

    @PreAuthorize("@ss.hasPermi('report:repaymentInfo:list')")
    @GetMapping("repaymentInfo/excel")
    @ApiOperation("还款信息表-excel")
    public void repaymentInfoExcel(@Valid RepaymentInfoBo repaymentInfoBo,
        HttpServletResponse response) {
        repaymentInfoBo.setPageNum(1);
        repaymentInfoBo.setPageSize(999999);
        Page<RepaymentInfoVo> repaymentInfoVoPage = reportService
            .getRepaymentInfoVoPage(repaymentInfoBo);
        if (repaymentInfoVoPage.getTotal() > 0) {
            List<RepaymentInfoVo> records = repaymentInfoVoPage.getRecords();
            records.forEach(record -> {
                RepaymentPlanParam repaymentPlanParam = new RepaymentPlanParam();
                BeanUtils.copyBeanProp(repaymentPlanParam, record);
                repaymentPlanParam.setFirstStatementDate(record.getFirstRepayDate());

                String lastRepaymentDate = record.getLastRepaymentDate();
                if (StringUtils.isBlank(lastRepaymentDate)) {
                    lastRepaymentDate = RepaymentPlanUtil
                        .getLastRepaymentDate(record.getGracePeriod(), record.getTerm(),
                            record.getFirstRepayDate());
                }

                record.setLastRepaymentDate(lastRepaymentDate);
                RepaymentPlan currentRepaymentPlan = RepaymentPlanUtil
                    .getCurrentRepaymentPlan(repaymentPlanParam,
                        LocalDate.parse(lastRepaymentDate));

                if (!currentRepaymentPlan.getTerm().equals(repaymentPlanParam.getTerm())) {
                    record.setCurrentTerm(currentRepaymentPlan.getTerm());
                    record.setRepayAmount(currentRepaymentPlan.getMonthRepayAmount());
                }
            });
        }
        InputStream templateExcelFile = excelFileUtil
            .getTemplateInputStream("repayment_info.xlsx");
        String exportFileName = "还款信息表" + LocalDate.now() + ".xlsx";
        ExcelExportUtil
            .exportByBeans(2, templateExcelFile, exportFileName, false, null,
                repaymentInfoVoPage.getRecords(),
                request, response);
    }

    private String getAdminName(Map<String, SysUser> redisUserMap, Long adminId) {
        if (null != adminId && adminId > 0) {
            SysUser sysUser = redisUserMap.get(adminId.toString());
            if (null != sysUser) {
                return sysUser.getUserName();
            }
        }
        return StringUtils.EMPTY;
    }

}
